﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using SnippetBox.Core.Common.Paging;
using SnippetBox.Core.Data.Models;

namespace SnippetBox.Core.Data.Service {
    public class UserService : ServiceBase<User> {
        private const int PAGE_SIZE = 10;

        public IPagedList<User> GetAllPaged(int? page) {
            return _repository.GetAll().OrderBy(x => x.DateCreated).ToPagedList(page, PAGE_SIZE);
        }

        public User GetByUsername(string username) {
            return _repository.GetAll().SingleOrDefault(u => u.Username == username);
        }

        public User GetByUsernameForProfile(string username) {
            return _repository.GetAll()
                .Include(u => u.Snippets)
                .Include(u => u.Favorites)
                .SingleOrDefault(u => u.Username == username);
        }

        public IPagedList<User> SearchByUsername(string query, int? page) {
            return _repository.Where(x => x.Username.Contains(query))
                .OrderBy(x => x.DateCreated)
                .ToPagedList(page, PAGE_SIZE);
        }

        public bool UsernameExists(string username, int? requestFromUserId) {
            var user = _repository.GetAll().SingleOrDefault(x => x.Username == username);
            
            if (user == null) 
                return false;

            if (requestFromUserId.HasValue && user.UserId == requestFromUserId.Value) 
                return false;

            return true;
        }
    }
}
